package com.ml.zookeeper.client;

import com.ml.zookeeper.lock.DistributedLock;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

/**
 * 客户端api示例
 * 连接、创建节点、获取节点、判断节点是否存在
 */
public class zkClient {

    // 注意：逗号左右不能有空格
    // private String connectString = "127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183"; //2888：通信的端口 3888：选举的端口
    private String connectString = "127.0.0.1:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zkClient;

    @Before
    public void init() throws IOException {

        zkClient = new ZooKeeper(connectString, sessionTimeout, watchedEvent -> {
            // 收到事件通知后的回调函数（用户的业务逻辑）
            System.out.println("--------------start------------");
            try {
                // 再次启动监听
                List<String> children = zkClient.getChildren("/", true);
                for (String child : children) {
                    System.out.println("second="+child);
                }

                System.out.println("-------------------------------");
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 创建节点
     *
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void create() throws KeeperException, InterruptedException {
        // 参数1:要创建的节点的路径; 参数2:节点数据; 参数3:节点权限; 参数4:节点的类型.
        String nodeCreated = zkClient.create("/atguigu", "ss.avi".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        //创建临时有序节点
//        String nodeCreated = zkClient.create("/locks/" + "seq-", null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
//        Thread.sleep(Long.MAX_VALUE);
        System.out.println(nodeCreated);
    }

    /**
     * 获取子节点，并监控数据的变化
     *
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void getChildren() throws KeeperException, InterruptedException {
        List<String> children = zkClient.getChildren("/", true);

        for (String child : children) {
            System.out.println("first="+child);
        }

        Thread.sleep(Long.MAX_VALUE);
    }

    /**
     * 判断节点是否存在
     *
     * @throws KeeperException
     * @throws InterruptedException
     */
    @Test
    public void exist() throws KeeperException, InterruptedException {
        Stat stat = zkClient.exists("/atguigu", false);
        System.out.println(stat == null ? "not exist " : "exist");
    }
}
